import java.util.Arrays;
public class MyArrayList {
    public int[] elem;
    public int usedSize;//0
    //默认容量
    private static final int DEFAULT_SIZE = 10;
    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }
    /**
     * 打印顺序表:
     * 根据usedSize判断即可
     */
    public void disPlay() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }
    // 新增元素,默认在数组最后新增
    public void add(int data) {
         if(isFull() == true) {
             this.elem = Arrays.copyOf(this.elem, this.elem.length * 2);
         }
         this.elem[usedSize] = data;
         this.usedSize++;
    }
    /**
     * 判断当前的顺序表是不是满的！
     */
    public boolean isFull() {
        if(this.elem.length == this.usedSize) {
            return true;
        }
        return false;
    }

    private boolean checkPos(int pos) {
        if((pos < 0) || (pos >= this.usedSize)) {//注意这里是pos>=this.usedSize
            throw new PosOutOfBoundsException(pos + "坐标不合法");
        }
        return  true;
    }
    // 获取pos位置的元素
    public int get(int pos) {
        checkPos(pos);
        return this.elem[pos];
    }
    // 在pos位置新增元素
    public void add(int pos, int data) {
        if((pos < 0) || (pos > this.usedSize)) {//注意这里是pos>this.usedSize
          throw new PosOutOfBoundsException(pos + "坐标不合法");
        }
        if(isFull() == true) {
            this.elem = Arrays.copyOf(this.elem, this.elem.length * 2);
        }
        for (int i = this.usedSize - 1; i >= pos ; i--) {
            this.elem[i + 1] = this.elem[i];//注意这里是this.elem[i + 1]不是this.elem[i++]
        }
        this.elem[pos] = data;
        this.usedSize++;
    }
    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    // 查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    private boolean isEmpty() {
         return this.usedSize == 0;
    }

    // 给 pos 位置的元素设为【更新为】 value
    public void set(int pos, int value) {
        checkPos(pos);
        this.elem[pos] = value;
    }

    /**
     *删除第一次出现的关键字key
     */
    public void remove(int key) {
        int index = indexOf(key);
        if(index == -1) {
            System.out.println("要移除的数据不存在");
            return;
        }
        for (int i = index; i < this.usedSize; i++) {
            this.elem[i] = this.elem[i + 1];//注意这里是this.elem[i + 1]不是this.elem[i++]
        }
        this.usedSize--;
    }

    // 获取顺序表长度
    public int size() {
          return this.usedSize;
    }

    // 清空顺序表
    public void clear() {
         this.usedSize = 0;
    }
}
